import React, { useState, useEffect } from 'react';
import { Container, Table, Form, Button, Badge, Card } from 'react-bootstrap';
import TodoService from '../services/TodoService';

const IncompleteTodosPage = () => {
    const [todos, setTodos] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        const fetchIncompleteTodos = async () => {
            try {
                setLoading(true);
                const response = await TodoService.getAllTodos();
                if (response.data && response.data.data) {
                    const incompleteTodos = response.data.data.filter(todo => !todo.complete);
                    setTodos(incompleteTodos);
                } else {
                    setError('获取任务列表失败，API返回格式不符合预期');
                }
            } catch (err) {
                setError('获取任务列表失败，请稍后再试');
                console.error('Error fetching incomplete todos:', err);
            } finally {
                setLoading(false);
            }
        };

        fetchIncompleteTodos();
    }, []);

    // 根据分类名生成不同的颜色
    const getCategoryColor = (category) => {
        if (!category) return 'secondary';

        // 简单的哈希函数生成颜色
        const colors = ['primary', 'success', 'info', 'warning', 'danger', 'dark'];
        const hash = category.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
        return colors[hash % colors.length];
    };

    const handleToggleComplete = async (todoId) => {
        try {
            const todo = todos.find(t => t.id === todoId);
            if (todo) {
                // 乐观更新UI
                const updatedTodos = todos.map(t =>
                    t.id === todoId ? { ...t, complete: !t.complete } : t
                );
                setTodos(updatedTodos);

                // 调用API更新状态
                await TodoService.updateTodo(todoId, { complete: !todo.complete });
            }
        } catch (err) {
            console.error('Error toggling todo status:', err);
            // 如果API调用失败，回滚UI更新
            const originalTodos = todos.map(t =>
                t.id === todoId ? { ...t, complete: !t.complete } : t
            );
            setTodos(originalTodos);
        }
    };

    const handleDeleteTodo = async (todoId) => {
        if (window.confirm('确定要删除这个待办事项吗？')) {
            try {
                // 乐观更新UI
                const updatedTodos = todos.filter(t => t.id !== todoId);
                setTodos(updatedTodos);

                // 调用API删除
                await TodoService.deleteTodo(todoId);
            } catch (err) {
                console.error('Error deleting todo:', err);
                // 如果API调用失败，回滚UI更新
                setTodos([...todos]);
            }
        }
    };

    return (
        <Container className="py-4">
            <h1 className="text-center mb-4">未完成的待办事项
                <Badge bg="primary" className="ms-2">{todos.length}</Badge>
            </h1>

            {error && <div className="alert alert-danger">{error}</div>}
            {loading ? (
                <div className="text-center p-5">
                    <div className="spinner-border text-primary" role="status">
                        <span className="visually-hidden">加载中...</span>
                    </div>
                    <p className="mt-2">正在加载任务...</p>
                </div>
            ) : todos.length === 0 ? (
                <Card className="text-center p-5 bg-light border-0 shadow-sm">
                    <Card.Body>
                        <Card.Title className="text-muted">暂无未完成的待办事项</Card.Title>
                        <Card.Text>所有任务都已完成！继续保持！</Card.Text>
                    </Card.Body>
                </Card>
            ) : (
                <Card className="shadow-sm">
                    <Table hover responsive className="mb-0">
                        <thead className="bg-light">
                        <tr>
                            <th style={{ width: "40%" }}>名称</th>
                            <th style={{ width: "20%" }}>分类</th>
                            <th style={{ width: "20%" }}>状态</th>
                            <th style={{ width: "20%" }}>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {todos.map((todo) => (
                            <tr key={todo.id} className={todo.complete ? 'bg-light' : ''}>
                                <td>
                                        <span className={todo.complete ? 'text-decoration-line-through text-muted' : 'fw-medium'}>
                                            {todo.name || '未命名任务'}
                                        </span>
                                </td>
                                <td>
                                    <Badge bg={getCategoryColor(todo.category)} pill>
                                        {todo.category || '默认'}
                                    </Badge>
                                </td>
                                <td>
                                    <Form.Check
                                        type="switch"
                                        id={`complete-switch-${todo.id}`}
                                        checked={todo.complete || false}
                                        onChange={() => handleToggleComplete(todo.id)}
                                        label={
                                            <Badge bg={todo.complete ? 'success' : 'warning'} pill>
                                                {todo.complete ? '已完成' : '进行中'}
                                            </Badge>
                                        }
                                    />
                                </td>
                                <td>
                                    <div className="d-flex gap-2">
                                        <Button
                                            variant="outline-primary"
                                            size="sm"
                                            // 这里暂时只实现删除功能，编辑功能需要更多上下文
                                            onClick={() => console.log('编辑任务:', todo.id)}
                                        >
                                            编辑
                                        </Button>
                                        <Button
                                            variant="outline-danger"
                                            size="sm"
                                            onClick={() => handleDeleteTodo(todo.id)}
                                        >
                                            删除
                                        </Button>
                                    </div>
                                </td>
                            </tr>
                        ))}
                        </tbody>
                    </Table>
                </Card>
            )}
        </Container>
    );
};

export default IncompleteTodosPage;